<?php

namespace app\command\tasks;

use app\helper\Log;
use app\common\services\EnergyService;
use app\common\repositories\energy\EnergyMeterRepository;
use app\common\repositories\energy\EnergyMeterDayRepository;
use app\common\repositories\energy\EnergyOperateLogRepository;

/**
 * 电表操作运行
 * Class ElectricOperateRunTask
 *
 * @package app\command\task
 */
class ElectricOperateRunTask
{
    protected function writeLog($str)
    {
        Log::writeLog('电表操作任务', $str, true);
    }

    /**
     * 执行任务
     * @return mixed
     */
    public function execute()
    {
        $this->writeLog('开始检测电表操作任务');
        while (true) {
            /** @var EnergyOperateLogRepository $operateLogRepository */
            $operateLogRepository = app()->make(EnergyOperateLogRepository::class);
            $list = $operateLogRepository->getSearch([])
                ->where('status', 1)
                ->where('energy_type', 11)
                ->where('energy_id', '>', 0)
                ->select();
            foreach ($list as $k => $v) {
                $this->sendRequest($v);
            }
            sleep(1);
        }
    }

    /**
     *  智能电表
     * @param $info
     * @return void
     * @throws \think\db\exception\DbException
     *
     * @author Amos
     * 2024-05-08 22:58
     */
    public function sendRequest($info)
    {
        $address = $info['energyMeterInfo']['energy_no'];
        $onoffType = $info['meterInfo']['onoff_type'] ?? 1;
        $this->writeLog("电表操作 " . $address . " " . $info['operate_type']);
        switch ($info['operate_type']) {
            case 'on': // 通电
                $server = EnergyService::init($info['items_id'])->Electric()->electricMeterControl($address, $onoffType == 2 ? 4 : 3);
                $res = $server->execute();
                // 通电成功
                if ($res && $res['code'] == 200 && $res['data']['status'] == 1 && $res['data']['response']['messageType'] == '阀控成功') {
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $energyMeterRepository->update($info['energy_id'], [
                        'on_off' => 1
                    ]);
                }
                break;
            case 'off': // 断电
                $server = EnergyService::init($info['items_id'])->Electric()->electricMeterControl($address, 2);
                $res = $server->execute();
                // 断电成功
                if ($res && $res['code'] == 200 && $res['data']['status'] == 1 && $res['data']['response']['messageType'] == '阀控成功') {
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $energyMeterRepository->update($info['energy_id'], [
                        'on_off' => 2
                    ]);
                }
                break;
            case 'call_status': # 召测状态
                $server = EnergyService::init($info['items_id'])->Electric()->electricMeterControl($address, 1);
                $res = $server->execute();
                // 查询状态成功
                if ($res && $res['code'] == 200 && $res['data']['status'] == 1 && $res['data']['response']['messageType'] == '电表运行状态') {
                    if ($res['data']['response']['messageData']['status'] == '通') {
                        $deviceStatus = 1;
                    } else {
                        $deviceStatus = 2;
                    }
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $energyMeterRepository->update($info['energy_id'], [
                        'on_off' => $deviceStatus
                    ]);
                }
                break;
            case 'call_reading': // 实时抄表
                $server = EnergyService::init($info['items_id'])->Electric()->electricMeterRealtimeRead($address, 1);
                $res = $server->execute();
                if ($res && $res['code'] == 200 && $res['data']['status'] == 1 && $res['data']['response']['messageType'] == '正向有功') {
                    $readingData = $res['data']['response']['messageData']['read'] ?? [];
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $energyMeterRepository->update($info['energy_id'], [
                        'status' => 1,
                        'read_z' => $readingData[0] ?? 0,
                        'read_j' => $readingData[1] ?? 0,
                        'read_f' => $readingData[2] ?? 0,
                        'read_p' => $readingData[3] ?? 0,
                        'read_g' => $readingData[4] ?? 0,
                        'read_time' => date('Y-m-d H:i:s')
                    ]);
                }
                break;
            case 'open_reading': ## 首次添加自动更新底数
                $server = EnergyService::init($info['items_id'])->Electric()->electricMeterRealtimeRead($address, 1);
                $res = $server->execute();
                if ($res && $res['code'] == 200 && $res['data']['status'] == 1 && $res['data']['response']['messageType'] == '正向有功') {
                    $readingData = $res['data']['response']['messageData']['read'] ?? [];
                    /** @var EnergyMeterRepository $energyMeterRepository */
                    $energyMeterRepository = app()->make(EnergyMeterRepository::class);
                    $energyMeterRepository->update($info['energy_id'], [
                        'status' => 1,
                        'read_z' => $readingData[0] ?? 0,
                        'read_j' => $readingData[1] ?? 0,
                        'read_f' => $readingData[2] ?? 0,
                        'read_p' => $readingData[3] ?? 0,
                        'read_g' => $readingData[4] ?? 0,
                        'read_time' => date('Y-m-d H:i:s')
                    ]);
                }
                break;
            default:
                $res = ['code' => 500, 'msg' => '操作类型不支持'];
                break;
        }
        /** @var EnergyOperateLogRepository $operateLogRepository */
        $operateLogRepository = app()->make(EnergyOperateLogRepository::class);
        if ($res && $res['code'] == 200) {
            $operateLogRepository->update($info['id'], [
                'result_time' => date('Y-m-d H:i:s'),
                'status' => 9,
                'result_content' => json_encode($res, JSON_UNESCAPED_UNICODE)
            ]);
        } else {
            $operateLogRepository->update($info['id'], [
                'result_time' => date('Y-m-d H:i:s'),
                'status' => 2,
                'fail_desc' => $res['msg'],
                'result_content' => json_encode($res, JSON_UNESCAPED_UNICODE)
            ]);
        }
    }

}
